#!/usr/bin/python2.5
"""This is the main file for GeoTree demo where points may be manually added and removed.
It includes classes for the first page and to fetch JSON data for tile.
"""

__author__ = 'Artem Dudarev'
__licence__ = 'Apache 2.0'
__date__ = 'Fri 19 Mar 2010 01:37:57 PM EET'

import os
import logging
import time
from django.utils import simplejson as json

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from geotree.geotree import GeoTree, Point
import geotree.geohash as geohash


def get_key(request_handler):
    """returns Google Maps API key string depending on the host URL
    """

    keys = { 
            'localhost' : 'ABQIAAAAwaGAdBqc0C3COmyw-rm7oBTwM0brOpm-All5BF6PoaKBxRWWERTFxDFb7R9qH1DEQBxVZtBZXnZQxw',
            'appspot' : 'YOUR_KEY_HERE'
           }

    url = request_handler.request.url

    if 'appspot' in url:
        key = keys['appspot']
    else:
        key = keys['localhost']
    return key


class InsertPoint(webapp.RequestHandler):
    def post(self):
        lat = self.request.get('lat').strip()
        lon = self.request.get('lng').strip()
        z = self.request.get('z').strip()
        # importance is sum of given importance 
        # and a number time.time()/2e9 < 1.0 until ~ year 2030
        # this way, a later submitted point with the same importance is slightly more important
        importance = float(self.request.get('importance').strip()) + time.time()/2e9
        update_one = self.request.get('update_one').strip()
        coord = "%s,%s" % (lat,lon)
        # key_name should be an application specific, here it is 8 character 64 bit word
        p = Point(key_name=geohash.encode_coord_str(coord),coord=coord,importance=importance,name='')
        p.put()
        GeoTree.insert_points_list([p])
        if update_one == 'false':
            GeoTree.update_tiles(10)
        gt = GeoTree.get()
        self.response.out.write('points - %s<br/>last tiles - %s' % (gt.number_points, gt.tiles_updated))


class RemovePoint(webapp.RequestHandler):
    def get(self):
        key_name = self.request.get('key_name').strip()
        debug_str = GeoTree.remove_point_by_key_name(key_name)
        self.response.out.write('Removing %s,<br/>%s' % (key_name,debug_str))


class GeoTreeInfo(webapp.RequestHandler):
    def get(self):
        gt = GeoTree.get()
        if gt:
            self.response.out.write('points - %s<br/>last tiles - %s' % (gt.number_points, gt.tiles_updated))


class GetTiles(webapp.RequestHandler):
    def get(self):
        center = self.request.get('c').strip()
        tiles = GeoTree.fetch_around_tile(center)
        self.response.out.write(tiles);


class MainHandler(webapp.RequestHandler):
    def get(self):
        map_key = get_key(self)
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path,{'map_key':map_key}))


logging.getLogger().setLevel(logging.DEBUG)
application = webapp.WSGIApplication([
                                    ('/', MainHandler),
                                    ('/t/', GetTiles),
                                    ('/insert_point', InsertPoint),
                                    ('/geo_tree_info', GeoTreeInfo),
                                    ('/remove_point', RemovePoint),
                                    ],
                                   debug=True)

def main():
    logging.getLogger().setLevel(logging.DEBUG)
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
